//
//  WYWRemoteResourceLoaderDelegate.m
//  WYWPlayer
//
//  Created by Mr.Run on 2017/11/9.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

#import "WYWRemoteResourceLoaderDelegate.h"
#import "WYWRemoteAudioFile.h"
#import "WYWAudioDownLoader.h"
#import "NSURL+Extension.h"

@interface WYWRemoteResourceLoaderDelegate ()<WYWAudioDownLoaderDelegate>

@property (nonatomic,strong) WYWAudioDownLoader *downloader;
@property (nonatomic,strong) NSMutableArray *loadingRequests;

@end

@implementation WYWRemoteResourceLoaderDelegate

- (WYWAudioDownLoader *)downloader{
    if (!_downloader) {
        _downloader = [[WYWAudioDownLoader alloc]init];
        _downloader.delegate = self;
    }
    return _downloader;
}

- (NSMutableArray *)loadingRequests{
    if (!_loadingRequests) {
        _loadingRequests = [NSMutableArray array];
    }
    return _loadingRequests;
}

-(BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForLoadingOfRequestedResource:(AVAssetResourceLoadingRequest *)loadingRequest{
    NSLog(@"%s~~~%d~~~%@",__func__,__LINE__,loadingRequest);
    
    NSURL *url = loadingRequest.request.URL;
    
    long long requestOffset = loadingRequest.dataRequest.requestedOffset;
    long long currentOffset = loadingRequest.dataRequest.currentOffset;
    
    if (requestOffset != currentOffset) {
        requestOffset = currentOffset;
    }
    
    if ([WYWRemoteAudioFile cacheFileExists:url]) {
        [self handleLoadingRequest:loadingRequest];
        return YES;
    }
    
    [self.loadingRequests addObject:loadingRequest];
    
    if (self.downloader.loadedSize == 0) {
        NSURL *httpURL = [url httpURL];
        [self.downloader downLoadWith:httpURL offset:requestOffset];
        return YES;
        
    }
    
    if (requestOffset < self.downloader.offset || requestOffset > (self.downloader.offset + self.downloader.loadedSize + 666)) {
        NSURL *httpURL = [url httpURL];
        [self.downloader downLoadWith:httpURL offset:requestOffset];
        return YES;
    }
    
    [self handleAllLoadingRequest];
    
    return YES;
}

-(void)resourceLoader:(AVAssetResourceLoader *)resourceLoader didCancelLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest{
    NSLog(@"%s~~~%d~~~取消摸个请求",__func__,__LINE__);
    [self.loadingRequests removeObject:loadingRequest];
}

-(void)downLoading{
    [self handleAllLoadingRequest];
}

-(void)handleAllLoadingRequest{
    NSLog(@"-----%@", self.loadingRequests);
//    NSLog(@"%s~~~%d~~~在这里不断处理请求数据",__func__,__LINE__);
    NSMutableArray *deleteRequests = [NSMutableArray array];
    for (AVAssetResourceLoadingRequest *loadingRequest in self.loadingRequests) {
        NSURL *url = loadingRequest.request.URL;
        loadingRequest.contentInformationRequest.contentLength = self.downloader.totalSize;
        loadingRequest.contentInformationRequest.contentType = self.downloader.mineType;
        loadingRequest.contentInformationRequest.byteRangeAccessSupported = YES;
        
        NSData *data = [NSData dataWithContentsOfFile:[WYWRemoteAudioFile tmpFilePath:url] options:NSDataReadingMappedIfSafe error:nil];
        
        if (data == nil) {
            data = [NSData dataWithContentsOfFile:[WYWRemoteAudioFile cacheFilePath:url] options:NSDataReadingMappedIfSafe error:nil];
        }
        
        long long requestOffset = loadingRequest.dataRequest.requestedOffset;
        long long currentOffset = loadingRequest.dataRequest.currentOffset;
        if (requestOffset != currentOffset) {
            requestOffset = currentOffset;
        }
        NSInteger requestLength = loadingRequest.dataRequest.requestedLength;
        
        long long responseOffset = requestOffset - self.downloader.offset;
        long long responseLength = MIN(self.downloader.offset + self.downloader.loadedSize - requestOffset, requestLength);
        
        NSData *subData = [data subdataWithRange:NSMakeRange(responseOffset, responseLength)];
        [loadingRequest.dataRequest respondWithData:subData];
        if (requestLength == responseLength) {
            [loadingRequest finishLoading];
            [deleteRequests addObject:loadingRequest];
        }
    }
    [self.loadingRequests removeObjectsInArray:deleteRequests];
}

-(void)handleLoadingRequest:(AVAssetResourceLoadingRequest *)loadingRequest{
    
    NSURL *url = loadingRequest.request.URL;
    long long totalSize = [WYWRemoteAudioFile cacheFileSize:url];
    
    loadingRequest.contentInformationRequest.contentLength = totalSize;
    NSString *contentType = [WYWRemoteAudioFile contentType:url];
    loadingRequest.contentInformationRequest.contentType = contentType;
    loadingRequest.contentInformationRequest.byteRangeAccessSupported = YES;
    
    NSData *data = [NSData dataWithContentsOfFile:[WYWRemoteAudioFile cacheFilePath:url] options:NSDataReadingMappedIfSafe error:nil];
    long long requestOffset = loadingRequest.dataRequest.requestedOffset;
    NSInteger requestLength = loadingRequest.dataRequest.requestedLength;
    
    NSData *subData = [data subdataWithRange:NSMakeRange(requestOffset, requestLength)];
    [loadingRequest.dataRequest respondWithData:subData];
    
    [loadingRequest finishLoading];
}

@end
